<template>
    <el-form
        ref="formRef"
        :model="formData"
        :rules="pageType == 'look' ? '' : rules"
        :label-width="create_type == 2 ? `100px` : `86px`"
        :disabled="pageType == 'look'">
        <el-form-item v-if="create_type == 2" label="选择公众号" prop="official_account_id">
            <OfficialAccounts
                :disabled="formDisabled"
                :public-data="{ id: formData.official_account_id, pageType }"
                @submit="v => v && (formData.official_account_id = v)" />
        </el-form-item>
        <el-form-item label="活动标题" prop="activity_name">
            <el-input
                v-model="formData.activity_name"
                class="w420"
                maxlength="15"
                show-word-limit
                placeholder="请输入标题名称" />
        </el-form-item>
        <el-form-item label="活动分组" prop="group_id">
            <el-cascader
                ref="cascaderRef"
                v-model="formData.group_id"
                :props="defaultProps"
                :options="groupOptions"
                style="width: 420px"
                @change="orgChange" />
        </el-form-item>
        <el-form-item label="活动有效期">
            <el-radio-group v-model="formData.period_type">
                <el-radio :label="1">永久</el-radio>
                <el-radio :label="2">固定期限</el-radio>
            </el-radio-group>
            <el-form-item v-if="formData.period_type === 2" prop="effect_date">
                <div v-if="formDisabled" class="edit-activity-time">
                    <el-date-picker
                        v-model="formData.effect_date[0]"
                        disabled
                        type="datetime"
                        format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        placeholder="开始时间" />
                    <el-date-picker
                        v-model="formData.effect_date[1]"
                        prefix-icon="none"
                        type="datetime"
                        format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        placeholder="结束时间"
                        :disabled-date="disabledDate"
                        :default-time="new Date(2000, 1, 1, 23, 59, 59)"
                        @change="checkActivityTime" />
                </div>
                <el-date-picker
                    v-else
                    v-model="formData.effect_date"
                    type="datetimerange"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                    range-separator="—"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    :default-time="defaultTime()"
                    :disabled-date="time => time.getTime() < Date.now() - 8.64e7" />
            </el-form-item>
        </el-form-item>
    </el-form>
</template>
<script lang="ts" setup>
import OfficialAccounts from '@/components/OfficialAccounts.vue';
import bus from '@/utils/bus';
import { getGroupList } from '@/api/concreation';
import { reactive, ref, watch, defineExpose, withDefaults, defineProps, inject } from 'vue';
import { ElMessage, FormInstance, FormRules } from 'element-plus';
import { useRoute } from 'vue-router';
import { defaultTime } from '@/utils/utils';

interface Props {
    pageType: any;
    group_id: any;
}
const props = withDefaults(defineProps<Props>(), {
    pageType: '',
    group_id: 0
});

/** 进行中、结束的情况下禁用 */
const formDisabled: any = inject('formDisabled');

const route = useRoute();
const create_type = inject('create_type');
const emit = defineEmits(['submit', 'theData']);
const formRef = ref<FormInstance>();
const cascaderRef: any = ref(null); // 选择分组ref
const groupOptions = ref([]);
const formData = ref({
    activity_name: '', // 活动标题
    group_id: props.group_id || 0, //分组ID //分组id
    period_type: 1, // 活动有效期 1-永久 2-固定
    effect_date: [], //  有效期
    official_account_id: ''
});

// 校验活动有效期
const timeValidator = (ruls: any, value: any, callback: any) => {
    const { period_type, effect_date } = formData.value;
    if (!period_type) {
        return callback(new Error('请选择活动有效期类型'));
    }

    if (period_type === 2) {
        const result = effect_date.every((item: any) => item);
        if (!result || effect_date.length < 2) return callback(new Error('请选择活动有效期'));

        // 校验结束时间和开始时间
        const [startTime, endTime] = effect_date;
        if (+new Date(startTime) >= +new Date(endTime)) {
            return callback(new Error('活动结束时间不能小于活动开始时间'));
        }
    }
    callback();
};

const rules = reactive<FormRules>({
    activity_name: [{ required: true, message: '请输入活动标题', trigger: 'blur' }],
    official_account_id: [{ required: true, message: '请选择公众号', trigger: 'blur' }],
    group_id: [{ required: true, message: '请选择活动分组', trigger: 'change' }],
    effect_date: [
        { required: true, message: '请选择活动有效期', trigger: 'blur' },
        { validator: timeValidator, trigger: 'blur' }
    ]
});
const defaultProps = {
    checkStrictly: true, // 是否严格的遵守父子节点不互相关联
    emitPath: false,
    multiple: false,
    label: 'name',
    value: 'id'
};

const disabledDate = (data: any) => {
    // 编辑状态下禁用活动创建之前
    if (formDisabled?.value && formData.value.created_at) {
        return +data < +new Date(formData.value.created_at) - 86400000;
    }
    // 86400000 => 一天的时间毫秒
    return +data < +new Date() - 86400000;
};

const checkActivityTime = () => {
    formRef.value?.validateField(['effect_date']);
};
// 获取活动分组
const onGroupgList = async () => {
    const res = await getGroupList({ type: 16, name: '' });
    groupOptions.value = res.data;
};
// 选择完地区后立即关闭
const orgChange = () => {
    cascaderRef.value.togglePopperVisible();
};
onGroupgList();
const onSubmit = async () => {
    if (!formRef.value) return;
    await formRef.value.validate((valid: any, fields: any) => {
        if (valid) {
            emit('submit');
        } else {
            ElMessage.warning(Object.values(fields)[0][0].message);
        }
    });
};
watch(
    formData,
    (v: any) => {
        bus.emit('one', v);
    },
    {
        deep: true
    }
);
defineExpose({
    formData,
    onSubmit
});
</script>

<style lang="scss" scoped>
.edit-activity-time {
    display: flex;
    width: 420px;

    :deep(.el-input__wrapper) {
        border: 1px solid var(--el-input-border-color);
        border-radius: 0;
        box-shadow: none;
    }

    :deep(.el-date-editor:first-child) {
        .el-input__wrapper {
            border-right: 0;
            border-radius: var(--el-input-border-radius) 0 0 var(--el-input-border-radius);
        }

        &::after {
            position: absolute;
            z-index: 2;
            right: 0;
            content: '-';
            transform: translateX(50%);
            color: #ccc;
        }
    }

    :deep(.el-date-editor:last-child) {
        .el-input__wrapper {
            border-left: 0;
            border-radius: 0 var(--el-input-border-radius) var(--el-input-border-radius) 0;
        }
    }

    :deep(.el-input__prefix) {
        margin-right: 6px;
    }
}

.w420 {
    width: 420px;
}
</style>
